#include "ui_son.h"
#include "ui_log.h"
#include "son.h"
#include "log.h"
#include "widget.h"
#include "ui_widget.h"
#include <cstdlib>
#include<QPainter>
#include <QMouseEvent>
#include <windows.h>
#include <QDesktopServices>
#include <windowsx.h>
#include <QDir>
#include <QPainter>
#include <QFileDialog>
#include <QMediaPlayer>
#include <QAudioOutput>
#include <QUrl>
#include <QMovie>
#include <QListWidget>
#include <QDebug>
#include <QList>


Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    this->setWindowFlags(Qt::Dialog|Qt::FramelessWindowHint);
    ui->setupUi(this);
    ui->horizontalSlider_2->setMaximum(100);
    ui->horizontalSlider_2->setMinimum(0);
    ui->horizontalSlider_2->setSingleStep(1);
    ui->horizontalSlider->setMinimum(0);
    ui->horizontalSlider->setSingleStep(1);
    audiooutput=new QAudioOutput(this);
    player =new QMediaPlayer(this);
    player->setAudioOutput(audiooutput);

    connect(player,&QMediaPlayer::durationChanged,this,[=](qint64 duration)
    {
        ui->lineEdit_2->setText("/"+QString::number(duration/60000)+":"+QString::number((duration/1000)%60));
        ui->horizontalSlider->setMaximum(duration);
    });

    connect(ui->pushButton_13,SIGNAL(clicked()),this,SLOT(toSon()));        //新窗口的按钮
    connect(&S,SIGNAL(sSignal()),this,SLOT(toMain()));          //返回main窗口
    connect(&S,SIGNAL(ansSignal()),this,SLOT(ans_yes()));

    connect(ui->pushButton_14,SIGNAL(clicked()),this,SLOT(tolog()));   //登录页面

    connect(player,&QMediaPlayer::positionChanged,this,[=](qint64 position)
    {
        ui->lineEdit_3->setText(QString::number(position/60000)+":"+QString::number((position/1000)%60));
        ui->horizontalSlider->setValue(player->position());
        if("/"+ui->lineEdit_3->text()==ui->lineEdit_2->text())
        {
            if(button9_pushed==0)    //顺序播放。。。默认
            {
                Widget::on_pushButton_4_clicked();
            }
            else if(button9_pushed==1)   //随机播放
            {
                srand(time(0));
                int randomplayid = rand()%(playlist.size());
                ui->listWidget->setCurrentRow(randomplayid);
                player->setSource(playlist[randomplayid]);
                player->play();
            }
            else if(button9_pushed==2)   //单曲循环
            {
                player->stop();
                player->play();
            }
        }
    });


    QFile file("C:/Users/X.J/Desktop/qt/player_v1/save.txt");             //记忆功能，基于在音乐存档文件中写入path
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QTextStream in(&file);
    while (!in.atEnd()){
        QString line = in.readLine();      //整行读取
        read_music_his(line);
    }
    if(player->isPlaying())
    {
        ui->pushButton_3->setStyleSheet("border-radius: 30px;border-image: url(:/buttom/playing.png);");
    }

}

Widget::~Widget()
{
    delete ui;
}

/*
void Widget::mousePressEvent(QMouseEvent *event)
{
    if(event->button() == Qt::LeftButton)
    {
        QLabel * label = new QLabel(this);
        QMovie * movie = new QMovie("C:/Users/X.J/Desktop/qt/player_v1/buttom/tp.gif");//加载gif图片
        //设置label自动适应gif的大小
        label->setScaledContents(true);

        label->setMovie(movie);
        //这里为了调用move方便，进行resize，需要知道的是gif的大小本来也就是150*150
        label->resize(150,150);
        //设置鼠标穿透
        label->setAttribute(Qt::WA_TransparentForMouseEvents, true);
        //让label的中心在当前鼠标双击位置
        label->move(event->pos().x()-label->width()/2,event->pos().y()-label->height()/2);
        //开始播放gif
        movie->start();

        label->show();

        //绑定QMovie的信号，判断gif播放次数
        connect(movie, &QMovie::frameChanged, [=](int frameNumber) {
            if (frameNumber == movie->frameCount() - 1)//gif播放次数为1，关闭标签
                label->close();
        });
    }
}
*/




void Widget::on_pushButton_3_clicked()  //开始
{
    switch(player->playbackState())
    {
        case QMediaPlayer::PlaybackState::StoppedState:    //未开始
        {
            ui->pushButton_3->setStyleSheet("border-radius: 30px;border-image: url(:/buttom/playing.png);");
            int index=ui->listWidget->currentRow();  //获取行号
            //播放对应下标的音乐
            player->setSource(playlist[index]);
            player->play();
            break;
        }
        case QMediaPlayer::PlaybackState::PlayingState:
        {
            ui->pushButton_3->setStyleSheet("border-radius: 30px;border-image: url(:/buttom/stop.png);");
            player->pause();
            break;
        }
        case QMediaPlayer::PlaybackState::PausedState:
        {
            ui->pushButton_3->setStyleSheet("border-radius: 30px;border-image: url(:/buttom/playing.png);");
            player->play();
            break;
        }
    }
}


void Widget::on_pushButton_clicked()     //选择音乐文件夹
{
    auto path=QFileDialog::getExistingDirectory(this,"请选择文件夹","C:\\");
    QDir dir(path);
    auto musiclist=dir.entryList(QStringList()<<"*.mp3"<<"*.wav");
    ui->listWidget->addItems(musiclist);      //把音乐名字放在list              //正在加入记忆功能
    for(auto file : musiclist)
    {
        playlist.append(QUrl::fromLocalFile(path+"/"+file));
        QFile qfile("C:/Users/X.J/Desktop/qt/player_v1/save.txt");
        qfile.open(QIODevice::ReadWrite | QIODevice::Text);
        qfile.write(path.toUtf8());
        qfile.close();
    }
    ui->listWidget->setCurrentRow(0);
}


void Widget::on_pushButton_5_clicked()   //音量按钮
{
    int nowvolume=audiooutput->volume();
    if(audiooutput->volume()!=0)
    {
        audiooutput->setVolume(0);
        ui->lineEdit->setText("0");
        ui->pushButton_5->setStyleSheet("border-radius: 15.5px;border-image: url(:/buttom/nosound.png);");
    }
    else if(audiooutput->volume()==0)
    {
        audiooutput->setVolume(ui->horizontalSlider_2->value()/100.0);
        ui->lineEdit->setText(QString::number(ui->horizontalSlider_2->value()));
        ui->pushButton_5->setStyleSheet("border-radius: 15.5px;border-image: url(:/buttom/sound.png);");
    }
}

/*
void Widget::on_verticalSlider_actionTriggered(int action)     //音量条
{
    auto volume=ui->verticalSlider->value()/100.0;
    ui->lineEdit->setText(QString::number(volume*100));
    int intvolume=QString(ui->lineEdit->text()).toInt();
    float truevolume=QString(ui->lineEdit->text()).toFloat();
    audiooutput->setVolume(truevolume/100.0);
    connect(audiooutput,&QAudioOutput::volumeChanged,this,[=](float vvolume)
    {
        ui->lineEdit->move(480,568-vvolume*100);
    });
}
*/

void Widget::on_horizontalSlider_2_actionTriggered(int action)
{
    auto volume=ui->horizontalSlider_2->value()/100.0;
    ui->lineEdit->setText(QString::number(volume*100));
    int intvolume=QString(ui->lineEdit->text()).toInt();
    float truevolume=QString(ui->lineEdit->text()).toFloat();
    audiooutput->setVolume(truevolume/100.0);
    connect(audiooutput,&QAudioOutput::volumeChanged,this,[=](float vvolume)
    {
       ui->lineEdit->move(989+vvolume*150,630);
    });
}


void Widget::on_pushButton_4_clicked()    //下一曲
{
    int now=ui->listWidget->currentRow();
    if(now==playlist.size()-1)
        now=-1;
    ui->listWidget->setCurrentRow(now+1);
    player->setSource(playlist[now+1]);
    miao=0,fen=0;
    player->play();
}


void Widget::on_pushButton_2_clicked()   //上一曲
{
    int now=ui->listWidget->currentRow();
    if(now==0)
        now=playlist.size();
    ui->listWidget->setCurrentRow(now-1);
    player->setSource(playlist[now-1]);
    miao=0,fen=0;
    player->play();
}



void Widget::on_listWidget_itemDoubleClicked(QListWidgetItem *item)  //实现列表内的双击
{
    player->setSource(playlist[ui->listWidget->currentRow()]);
    player->play();
}


void Widget::on_horizontalSlider_actionTriggered(int action)    //进度条
{
    //fakeduration
    qint64 nowposition=ui->horizontalSlider->value();
    player->setPosition(nowposition);
}



void Widget::on_pushButton_6_clicked()    //更换壁纸
{
    filename = QFileDialog::getOpenFileName(this,QStringLiteral("文件对话框！"),"C:",QStringLiteral("图片文件(*png *jpg)"));
    QFile qfile("C:/Users/X.J/Desktop/qt/player_v1/save_bg.txt");
    qfile.open(QIODevice::ReadWrite | QIODevice::Text);
    qfile.write(filename.toUtf8());
    qfile.close();
}

void Widget::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.drawPixmap(0,0,width(),height(),QPixmap(filename));
}

void Widget::on_pushButton_7_clicked()     //隐藏UI
{
    if(ui->horizontalSlider->isVisible())
    {
        ui->horizontalSlider->setVisible(0);
        ui->lineEdit->setVisible(0);
        ui->lineEdit_2->setVisible(0);
        ui->lineEdit_3->setVisible(0);
        ui->listWidget->setVisible(0);
        ui->pushButton->setVisible(0);
        ui->pushButton_2->setVisible(0);
        ui->pushButton_3->setVisible(0);
        ui->pushButton_4->setVisible(0);
        ui->pushButton_5->setVisible(0);
        ui->pushButton_6->setVisible(0);
        ui->horizontalSlider_2->setVisible(0);
        ui->pushButton_9->setVisible(0);
    }
    else
    {
        ui->horizontalSlider->setVisible(1);
        ui->lineEdit->setVisible(1);
        ui->lineEdit_2->setVisible(1);
        ui->lineEdit_3->setVisible(1);
        ui->listWidget->setVisible(1);
        ui->pushButton->setVisible(1);
        ui->pushButton_2->setVisible(1);
        ui->pushButton_3->setVisible(1);
        ui->pushButton_4->setVisible(1);
        ui->pushButton_5->setVisible(1);
        ui->pushButton_6->setVisible(1);
        ui->horizontalSlider_2->setVisible(1);
        ui->pushButton_9->setVisible(1);
    }
}


void Widget::on_pushButton_9_clicked()     //播放模式的切换
{
    //0代表顺序播放，1代表随机播放，2代表单曲循环
    if(button9_pushed==0)
    {
        //随机数
        ui->pushButton_9->setStyleSheet("image: url(:/buttom/random.png); background-color: rgb(240, 240, 240);");
        button9_pushed=1;
    }
    else if(button9_pushed==1)
    {
        ui->pushButton_9->setStyleSheet("image: url(:/buttom/circle.png); background-color: rgb(240, 240, 240);");
        button9_pushed=2;
    }
    else if(button9_pushed==2)
    {
        ui->pushButton_9->setStyleSheet("image: url(:/buttom/order.png); background-color: rgb(240, 240, 240);");
        button9_pushed=0;
    }
}

void Widget::on_pushButton_8_clicked()    //退出
{
    this->close();
}

void Widget::on_pushButton_10_clicked()   //最小化
{
    this->showMinimized();
}

void Widget::on_pushButton_12_clicked()  //关于跳转
{
    const QUrl regUrl(QLatin1String("https://gitee.com/Xu-zhiyuan0721/qtplayer"));
    QDesktopServices::openUrl(regUrl);
}


void Widget::on_pushButton_13_clicked()       //新窗口按钮
{

}

void Widget::toSon()
{
    S.show();
}

void Widget::tolog()
{
    L.show();
}

void Widget::sontoMain()
{
    S.close();
}

void Widget::logtoMain()
{
    L.close();
}

void Widget::ans_yes()          //son窗口答案正确后
{
    const QUrl regUrl(QLatin1String("https://0d00.cn/"));
    QDesktopServices::openUrl(regUrl);
    playlist.append(QUrl::fromLocalFile("C:\\Users\\X.J\\Desktop\\qt\\player_v1\\恋せよ乙女!——yuzusoft.mp3"));
    player->setSource(QUrl::fromLocalFile("C:\\Users\\X.J\\Desktop\\qt\\player_v1\\恋せよ乙女!——yuzusoft.mp3"));
    player->play();
}

void Widget::read_music_his(QString path)               //读取音乐历史
{
    if(path!=" ")
    {
        QDir dir(path);
        auto musiclist=dir.entryList(QStringList()<<"*.mp3"<<"*.wav");
        ui->listWidget->addItems(musiclist);
        for(auto file : musiclist)
        {
            playlist.append(QUrl::fromLocalFile(path+"/"+file));
        }
        ui->listWidget->setCurrentRow(0);
    }
}

void Widget::on_pushButton_14_clicked()        //登录按钮
{

}

